package com.chenqi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenqi.dao.*;
import com.chenqi.model.dto.PostDTO;
import com.chenqi.model.entity.Comment;
import com.chenqi.model.entity.Post;
import com.chenqi.model.entity.Tag;
import com.chenqi.model.entity.User;
import com.chenqi.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description: 帖子业务实现层
 * @program: ardaicommunity
 * @author: ChenQi
 * @create: 2021-03-2021/3/11-14-39
 */
@Slf4j
@Service
@Transactional(rollbackFor = {Exception.class})
public class PostServiceImpl implements PostService {

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private PostTagMapper postTagMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public List<Post> getPostByPage( Integer page, Integer rows, Integer sectionId) {
        //处理索引
        int start = (page - 1) * rows;
        List<Post> postByPage = postMapper.getPostByPage(start, rows, sectionId);
        return postByPage;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public Integer counts(Integer sectionId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("section_id", sectionId);
        Integer total = postMapper.selectCount(queryWrapper);
        return total;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
    public int addPost(PostDTO postDTO) {
        try {
            Post post = new Post();
            post.setTitle(postDTO.getTitle())
                    .setContent(postDTO.getContent())
                    .setUserId(postDTO.getUserId())
                    .setComments(0)
                    .setCollects(0)
                    .setView(0)
                    .setTop(0)
                    .setEssence(0)
                    //暂时默认添加进默认专栏
                    .setSectionId(0)
                    .setCreateTime(new Date())
                    .setModifyTime(new Date());
            String[] tags = postDTO.getTags();
            for (int i = 0; i < tags.length; i++) {
                //先去数据库查找有没有对应的标签
                QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("name", tags[i]);
                Integer count = tagMapper.selectCount(queryWrapper);
                //如果为0就说明是新标签，就添加进去
                if (count == 0){
                    Tag tag = new Tag();
                    tag.setName(tags[i]).setTopicCount(0);
                    tagMapper.insert(tag);
                }else {
                    //如果不为0就说明当前标签数据库有，就让topic_count+1
                    Tag tag = tagMapper.selectOne(queryWrapper);
                    tag.setTopicCount(tag.getTopicCount() + 1);
                    tagMapper.update(tag, queryWrapper);
                }
            }
            //插入数据
            postMapper.insert(post);
            //修改帖子用户的帖子数量
            User user = userMapper.selectById(postDTO.getUserId());
            user.setPostCount(user.getPostCount()+1);
            userMapper.updateById(user);
            //维护帖子和标签的关系
            for (int i = 0; i < tags.length; i++) {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("name",tags[i]);
                Tag tag = tagMapper.selectOne(queryWrapper);
                postTagMapper.insertPostIdAndTagsId(post.getId(), tag.getId());
            }
            return 1;
        }catch (Exception e){
            log.error("Exception:{}",e.getMessage());
            return 0;
        }
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public Post getPostById(Integer id) {
        //查看详情的时候对帖子查看次数进行添加
        Post postById = postMapper.getPostById(id);
        postById.setView(postById.getView()+1);
        postMapper.updateById(postById);
        //获取对应的标签
        List<Integer> tagsByPostId = postTagMapper.findTagsByPostId(id);
        List<Tag> tagList = new ArrayList<>();
        for (Integer tagId : tagsByPostId) {
            Tag tag = tagMapper.selectById(tagId);
            tagList.add(tag);
        }
        postById.setTagList(tagList);
        return postById;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public List<Post> recommend() {
        List<Post> recommends = postMapper.recommend();
        return recommends;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
    public int removePost(Integer pid) {
        try{
            //删除帖子
            int i = postMapper.deleteById(pid);
            //删除对应的评论
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("post_id", pid);
            commentMapper.delete(queryWrapper);
            //删除对应的标签
            postTagMapper.delete(queryWrapper);
            return i;
        }catch (Exception e){
            log.error("Exception:{}", e.getMessage());
            return 0;
        }
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public List<Post> search(String title) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like("title",title);
        List list = postMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public List<Post> getPostByUserId(Integer id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", id);
        List list = postMapper.selectList(queryWrapper);
        return list;
    }


}
